//
//  SHWeiBoManager.m
//  SHWeiBo
//
//  Created by 索晓晓 on 2021/10/29.
//

#import "SHWeiBoManager.h"
#import <RCWeibo_SDK/WeiboSDK.h>

@interface SHWeiBoManager ()<WeiboSDKDelegate,WBMediaTransferProtocol>

@property (nonatomic , strong) NSString *wbtoken;
@property (nonatomic , strong) NSString *wbCurrentUserID;
@property (nonatomic , strong) NSString *wbRefreshToken;
@property (nonatomic , strong) NSString *redirectURI;

@property (nonatomic , strong) void (^loginComplateBlock)(NSDictionary *info);

@end

@implementation SHWeiBoManager

+ (instancetype)sharedInstance {
    static SHWeiBoManager * instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[SHWeiBoManager alloc] init];
    });
    return instance;
}

/**
 向微博客户端程序注册第三方应用
 @param appKey 微博开放平台第三方应用appKey
 @param universalLink 开发者Universal Link
 @return 注册成功返回YES，失败返回NO
 */
+ (BOOL)registerApp:(NSString * __nonnull)appKey
        redirectURI:(NSString * __nonnull)redirectURI
      universalLink:(NSString * __nonnull)universalLink {
    [SHWeiBoManager sharedInstance].redirectURI = redirectURI;
    return [WeiboSDK registerApp:appKey universalLink:universalLink];
}


/// 处理applicatin:optnUrl
/// @param url url
+ (BOOL)handleURL:(NSURL*)url {
    return [WeiboSDK handleOpenURL:url delegate:[SHWeiBoManager sharedInstance]];
}

/*! @brief 处理微博通过Universal Link启动App时传递的数据
 *
 * 需要在 application:continueUserActivity:restorationHandler:中调用。
 * @param userActivity 微博启动第三方应用时系统API传递过来的userActivity
 * @return 成功返回YES，失败返回NO。
 */
+ (BOOL)handleOpenUniversalLink:(NSUserActivity *_Nullable)userActivity {
    return [WeiboSDK handleOpenUniversalLink:userActivity delegate:[SHWeiBoManager sharedInstance]];
}


#pragma mark - WBMediaTransferProtocol
/**
 数据准备成功回调
 */
-(void)wbsdk_TransferDidReceiveObject:(id _Nullable )object {
    
}

/**
 数据准备失败回调
 */
-(void)wbsdk_TransferDidFailWithErrorCode:(WBSDKMediaTransferErrorCode)errorCode andError:(NSError*_Nullable)error {
    
}


#pragma mark - WeiboSDKDelegate
- (void)didReceiveWeiboRequest:(WBBaseRequest *)request
{
    
}

- (void)didReceiveWeiboResponse:(WBBaseResponse *)response
{
    if ([response isKindOfClass:WBSendMessageToWeiboResponse.class]) {
        WBSendMessageToWeiboResponse* sendMessageToWeiboResponse = (WBSendMessageToWeiboResponse*)response;
        NSString* accessToken = [sendMessageToWeiboResponse.authResponse accessToken];
        if (accessToken)
        {
            self.wbtoken = accessToken;
        }
        NSString* userID = [sendMessageToWeiboResponse.authResponse userID];
        if (userID) {
            self.wbCurrentUserID = userID;
        }
        
    }
    else if ([response isKindOfClass:WBAuthorizeResponse.class])
    {
//        WeiboSDKResponseStatusCodeSuccess               = 0,//成功
//        WeiboSDKResponseStatusCodeUserCancel            = -1,//用户取消发送
//        WeiboSDKResponseStatusCodeSentFail              = -2,//发送失败
//        WeiboSDKResponseStatusCodeAuthDeny              = -3,//授权失败
//        WeiboSDKResponseStatusCodeUserCancelInstall     = -4,//用户取消安装微博客户端
//        WeiboSDKResponseStatusCodeShareInSDKFailed      = -8,//分享失败 详情见response UserInfo
//        WeiboSDKResponseStatusCodeUnsupport             = -99,//不支持的请求
//        WeiboSDKResponseStatusCodeUnknown               = -100,
        if(response.statusCode == WeiboSDKResponseStatusCodeSuccess){
            
            
            self.wbtoken = [(WBAuthorizeResponse *)response accessToken];
            self.wbCurrentUserID = [(WBAuthorizeResponse *)response userID];
            self.wbRefreshToken = [(WBAuthorizeResponse *)response refreshToken];
            
            if([SHWeiBoManager sharedInstance].loginComplateBlock){
                [SHWeiBoManager sharedInstance].loginComplateBlock(@{@"isSuccess":@(true),
                                                                     @"token":self.wbtoken,
                                                                     @"userId":self.wbCurrentUserID,
                                                                     @"refreshToken":self.wbRefreshToken,
                                                                     @"message":@"授权成功"
                                                                   });
                [SHWeiBoManager sharedInstance].loginComplateBlock = nil;
            }
        } else {
            if([SHWeiBoManager sharedInstance].loginComplateBlock){
                
                [SHWeiBoManager sharedInstance].loginComplateBlock(@{@"isSuccess":@(false),
                                                                     @"message":@"授权失败"
                                                                   });
                [SHWeiBoManager sharedInstance].loginComplateBlock = nil;
            }
        }
        
        
        
    }if([response isKindOfClass:WBShareMessageToContactResponse.class]) {
        
        WBShareMessageToContactResponse* shareMessageToContactResponse = (WBShareMessageToContactResponse*)response;
        NSString* accessToken = [shareMessageToContactResponse.authResponse accessToken];
        if (accessToken)
        {
            self.wbtoken = accessToken;
        }
        NSString* userID = [shareMessageToContactResponse.authResponse userID];
        if (userID) {
            self.wbCurrentUserID = userID;
        }
    }
}


+ (void)goLogin:(void (^)(NSDictionary *info))complate {
    
    
    [SHWeiBoManager sharedInstance].loginComplateBlock = complate;
    
    WBAuthorizeRequest *request = [WBAuthorizeRequest request];
    request.redirectURI = [SHWeiBoManager sharedInstance].redirectURI;
    request.scope = @"all";
    //下面两句测试打开ituns网页
    request.shouldShowWebViewForAuthIfCannotSSO = YES;
//    request.shouldOpenWeiboAppInstallPageIfNotInstalled = false;
    [WeiboSDK sendRequest:request completion:nil];
}


/// 分享纯文本
/// @param title 文本
+ (void)shareTitle:(NSString *)title {
    
    WBMessageObject *message = [WBMessageObject message];
    message.text = title;
    
    WBAuthorizeRequest *authRequest = [WBAuthorizeRequest request];
    authRequest.redirectURI = [SHWeiBoManager sharedInstance].redirectURI;
    authRequest.scope = @"all";
    
    WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:message authInfo:authRequest access_token:[SHWeiBoManager sharedInstance].wbtoken];
    
    [WeiboSDK sendRequest:request completion:^(BOOL success) {
        
    }];
    
}

/// 分享纯图片
/// @param image 图片
+ (void)shareImage:(UIImage *)image {
    
    WBMessageObject *message = [WBMessageObject message];
    WBImageObject *imageObject = [WBImageObject object];
    imageObject.delegate = self;
    [imageObject addImages:@[image]];
    message.imageObject = imageObject;
    
    WBAuthorizeRequest *authRequest = [WBAuthorizeRequest request];
    authRequest.redirectURI = [SHWeiBoManager sharedInstance].redirectURI;
    authRequest.scope = @"all";
    
    WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:message authInfo:authRequest access_token:[SHWeiBoManager sharedInstance].wbtoken];

    [WeiboSDK sendRequest:request completion:^(BOOL success) {
        
    }];
    
}


/// 分享资讯到微博
/// @param title 标题
/// @param description 描述
/// @param thumbnailImage 缩略图
/// @param webpageUrl 跳转链接
+ (void)shareTitle:(NSString *)title
       description:(NSString *)description
     thumbnailData:(UIImage *)thumbnailImage
        webpageUrl:(NSString *)webpageUrl {
    
    WBMessageObject *message = [WBMessageObject message];
    
    message.text = title;
    WBImageObject *imageObject = [WBImageObject object];
    imageObject.imageData = UIImageJPEGRepresentation(thumbnailImage, 0.3);
    imageObject.delegate = self;
    message.imageObject = imageObject;
    
    WBAuthorizeRequest *authRequest = [WBAuthorizeRequest request];
    authRequest.redirectURI = [SHWeiBoManager sharedInstance].redirectURI;
    authRequest.scope = @"all";
    
    WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:message authInfo:authRequest access_token:[SHWeiBoManager sharedInstance].wbtoken];

    [WeiboSDK sendRequest:request completion:^(BOOL success) {

    }];
    
}



@end
